package Java基础.Concurrent;

import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhengqiang.tan
 * @Date 2020/10/15 2:55 PM
 * @Version 1.0
 * <p>
 * <p>
 * <p>
 * 使用 LinkedBlockingQueue 实现的一个简单生产者和消费者实例，在很多互联网的笔试环节，这个题目会经常出现。
 * 可以看到，我们还使用了一个 volatile 修饰的变量，来决定程序是否继续运行，这也是 volatile 变量的常用场景
 */
public class ProducerConsumerTest {

    private LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
    private volatile boolean stop = false;

    Runnable producer = () -> {
        while (!stop) {
            try {
                queue.offer(UUID.randomUUID().toString(), 1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {

            }
        }
    };

    Runnable consummer = () -> {
        while (!stop) {
            String take = null;
            try {
                take = queue.take();
                System.out.println(Thread.currentThread().getName() + "|" + take);
            } catch (InterruptedException e) {
            }
        }
    };

    void start() {
        new Thread(producer, "thread 1").start();
        new Thread(producer, "thread 2").start();
        new Thread(consummer, "thread 3").start();
        new Thread(consummer, "thread 4").start();
    }

    public static void main(String[] args) {
        new ProducerConsumerTest().start();
    }

}
